package com.tuanbiao.ui.account;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.jakewharton.rxbinding4.view.RxView;
import com.tuanbiao.AppConfig;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.constants.UserConstants;
import com.tuanbiao.controllers.AccountController;
import com.tuanbiao.databinding.ActivityLoginBinding;
import com.tuanbiao.dialog.BaseDialog;
import com.tuanbiao.dialog.InputDialog;
import com.tuanbiao.events.OfflineRegisterEvent;
import com.tuanbiao.events.SettingDeviceEvent;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.keyevent.listener.OnLoginKeyDownListener;
import com.tuanbiao.models.AccountModel;
import com.tuanbiao.presenter.account.LoginPresenter;
import com.tuanbiao.ui.MainActivity;
import com.tuanbiao.ui.SettingMacActivity;
import com.tuanbiao.ui.setting.SettingDeviceActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;


/**
 * 登录
 */
public class LoginActivity extends BasePresenterActivity<LoginPresenter, ActivityLoginBinding> implements AccountController.LoginView {

    private ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == RESULT_OK && null != result.getData()) {
                binding.etLoginIdCard.setText(result.getData().getStringExtra("_ID_CARD_"));
                binding.etLoginPassword.setText(result.getData().getStringExtra("_PASSWORD_"));
            }
        }
    });

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        starter.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(starter);
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(new AccountModel(), this);
    }

    @Override
    protected ActivityLoginBinding getBindingView() {
        return ActivityLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        binding.btnLoginCommit.setEnabled(true);
        RxView.clicks(binding.btnLoginCommit).throttleFirst(1, TimeUnit.MICROSECONDS)
                .subscribe(unit -> {
                    mPresenter.login(getString(binding.etLoginIdCard), getString(binding.etLoginPassword));
                });
        RxView.clicks(binding.tvLoginRegister).throttleFirst(1, TimeUnit.MICROSECONDS)
                .subscribe(unit -> {
                    String idCard = getString(binding.etLoginIdCard);
                    if (!TextUtils.isEmpty(idCard))
                        EventBus.getDefault().postSticky(new OfflineRegisterEvent(idCard));
                    launcher.launch(OfflineRegisterActivity.createIntent(getActivity()));
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        KeyEventHelper.getInstance().checkLoginKeyDown(keyCode, new OnLoginKeyDownListener() {
            @Override
            public void onChangeMacIMEI() {
                showMacSettingDialog();
            }

            @Override
            public void onChangeDeviceNum() {
                showChangePasswordDialog();
            }
        });
        return super.onKeyDown(keyCode, event);
    }

    private void showMacSettingDialog() {
        if (AppConfig.showPassword()) {
            startMacSetting();
        } else {
            new InputDialog.Builder(getActivity())
                    .setTitle("提示")
                    .setHint("请输入密码")
                    .setAutoDismiss(false)
                    .setListener(new InputDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog, String content) {
                            if (TextUtils.isEmpty(content)) {
                                showMessage("请输入密码");
                                return;
                            }
                            mPresenter.checkMacSettingPassword(content);
                            dialog.dismiss();
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    }

    private void showChangePasswordDialog() {
        if (AppConfig.showPassword()) {
            startDeviceSetting(UserConstants.Type.DEVELOP);
        } else {
            new InputDialog.Builder(getActivity())
                    .setTitle("提示")
                    .setHint("请输入密码")
                    .setAutoDismiss(false)
                    .setListener(new InputDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog, String content) {
                            if (TextUtils.isEmpty(content)) {
                                showMessage("请输入密码");
                                return;
                            }
                            mPresenter.checkPassword(content);
                            dialog.dismiss();
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            dialog.dismiss();
                        }
                    }).show();
        }

    }


    @Override
    public void startMain() {
        MainActivity.start(getActivity());
        killMyself();
    }

    @Override
    public void showLoginInfo(String idCard, String password) {
        binding.etLoginIdCard.setText(idCard);
        binding.etLoginPassword.setText(password);
    }

    @Override
    public void showUserName(String userName) {
        binding.etLoginIdCard.setText(userName);
    }

    @Override
    public void startDeviceSetting(@UserConstants.KeyEventUserType int type) {
        EventBus.getDefault().postSticky(new SettingDeviceEvent(type));
        SettingDeviceActivity.start(getActivity());
    }

    @Override
    public void startMacSetting() {
        SettingMacActivity.start(getActivity());
    }

    @Override
    public void showAppVersion(String versionName) {
        binding.tvAppVersion.setText(versionName);
    }
}
